<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Ajax请求</title>
		<style>
			#emp {
				border-collapse: collapse;
			}
			#emp td, #emp th {
				border-bottom: 1px solid black;
				width: 120px;
				text-align: center;
			}
			#page {
				width: 720px;
				text-align: center;
			}
			#page a {
				text-decoration: none;
				color: darkcyan;
			}
		</style>
	</head>
	<body>
		<table id="emp">
			<thead>
				<tr>
					<th>编号</th>
					<th>姓名</th>
					<th>职位</th>
					<th>工资</th>
					<th>补贴</th>
					<th>所在部门</th>
				</tr>
			</thead>
			<tbody>
			</tbody>
		</table>
		<div id="page">
			<a id="prev" href="">上一页</a>&nbsp;&nbsp;
			<a id="next" href="">下一页</a>
		</div>
		<script src="js/jquery.min.js"></script>
		<script>
		$(() => {
			function getEmpData(url) {
				$.ajax({
					url: url,
					type: 'get',
					data: {},
					dataType: 'json',
					headers: {
						"token": "35ad60445cea11e99e1000163e02b646"
					},
					success: (json) => {
						$('#emp>tbody').empty()
						json.results.forEach((emp) => {
							let tr = $('<tr>')
								.append($('<td>').text(emp.no))
								.append($('<td>').text(emp.name))
								.append($('<td>').text(emp.job))
								.append($('<td>').text(emp.sal))
								.append($('<td>').text(emp.comm))
								.append($('<td>').text(emp.dept.name))
							$('#emp>tbody').append(tr)
						})
						$('#prev').attr('href', json.previous? json.previous : '')
						$('#next').attr('href', json.next? json.next : '')
					}
				})
			}
			
			function changePage(evt) {
				evt.preventDefault()
				let href = $(evt.target).attr('href')
				if (href) {
					getEmpData(href)
				}
			}
			
			getEmpData('http://120.77.222.217/api/emps/')
			
			$('#prev').on('click', changePage)
			$('#next').on('click', changePage)
		})
		</script>
	</body>
</html>
